import Axios from "axios";
import Config from "@/config";
const httpConfig = Config.http
let { baseURL, timeout
} = httpConfig
import UserTokenModule from "@/tools/token"
// 实例化Axios
let instance = Axios.create({ baseURL, timeout });
// 请求拦截器
instance.interceptors.request.use((req) => {

  // 请求是否携带Token
  let {
    RequestCarryToken,
    RequestCarryTokenPosition,
    RequestCarryTokenPositionKey
  } = Config.http

  if (RequestCarryToken) {
    let UserToken = UserTokenModule.getUserToken()
    if (UserToken) {
      if (RequestCarryTokenPosition == "headers") {
        req.headers[RequestCarryTokenPositionKey] = UserToken ?? null;
      } else if (RequestCarryTokenPosition == "body") {
        req.body[RequestCarryTokenPositionKey] = UserToken ?? null;
      }
    }
  }
  return req;
});
// 响应拦截器
instance.interceptors.response.use(
  (res) => {
    if (res.data.code == 0) {
      return res.data;
    } else {
      return Promise.reject(res.data);
    }
  },
  (err) => {
    let message = err.message;
    let code = err.code;
    if (message == "Network Error") {
      return Promise.reject({
        code: 500,
        msg: "服务器无法访问",
      });
    } else if (code == "ECONNABORTED") {
      return Promise.reject({
        code: 500,
        msg: "请求超时",
      });
    } else if (message == "Request failed with status code 404") {
      return Promise.reject({
        code: 404,
        msg: "接口不存在",
      });
    } else {
      return Promise.reject({
        code: 5003,
        msg: "接口请求出错,未知错误",
      });
    }
  }
);
export default instance;
